<template>
	<div>
		<Plan
			ref="Plan"
			v-model="infoData"
			:state="state"
			:type="type"
			@setConfig="setConfig"></Plan>
		<InfoApply
			ref="Info"
			v-model="infoData"
			:state="state"
			:type="type"></InfoApply>

		<Insurance
			ref="Insurance"
			v-model="infoData.productList[0]"
			:planDicts="planDicts"
			:state="state"></Insurance>
		<!-- 维保 -->
		<Maintain
			ref="Maintain"
			v-model="infoData.productList[0]"
			:planDicts="planDicts"
			:state="state"
			:type="type"
			:index="0"></Maintain>
		<!-- <MaintainPrice -->
		<!-- ref="MaintainPrice" -->
		<!-- :planDicts="planDicts" -->
		<!-- v-model="infoData.productList[0]" -->
		<!-- :state="state" -->
		<!-- :index="0" -->
		<!-- :type="type"></MaintainPrice> -->
		<!-- <InsurancePrice -->
		<!-- ref="InsurancePrice" -->
		<!-- :planDicts="planDicts" -->
		<!-- v-model="infoData.productList[0]" -->
		<!-- :state="state" -->
		<!-- :index="0" -->
		<!-- :type="type"></InsurancePrice> -->
		<ContractPreview
			v-if="type == 'preview'"
			v-model="infoData"
			ref="contract"
			:state="state"></ContractPreview>
		<Contract
			v-else
			v-model="infoData"
			ref="contract"
			:state="state"
			:type="type"
			:key="infoData.schemeId"></Contract>

		<CarInfo
			v-if="
				infoData &&
				infoData.productList &&
				infoData.productList.length > 0
			"
			ref="CarInfo"
			v-model="infoData"
			:cityList="cityList"
			:state="state"
			:planDicts="planDicts"
			:type="type"></CarInfo>
	</div>
</template>

<script>
	import * as app from '@/api/app.js';
	import * as apis from '@/api/quota/forecast/edit/api.js';
	import { regionList } from '@/api/system/dept.js';
	import Plan from '@/views/quota/forecast/chunk/plan';
	import InfoApply from '@/views/quota/forecast/chunk/info_apply';
	import Contract from '@/views/quota/forecast/chunk/contract';
	import ContractPreview from '@/views/quota/forecast/chunk/contractPreview';
	import CarInfo from '@/views/quota/forecast/chunk/carInfo/indexAll.vue';
	import Insurance from '@/views/quota/forecast/chunk/insurance/index.vue';
	import Maintain from '@/views/quota/forecast/chunk/maintain/index.vue';
	import MaintainPrice from '@/views/quota/forecast/chunk/maintainPrice/index.vue';
	import InsurancePrice from '@/views/quota/forecast/chunk/insurancePrice/index.vue';

	export default {
		components: {
			Plan,
			InfoApply,
			Contract,
			CarInfo,
			ContractPreview,
			Insurance,
			Maintain,
			MaintainPrice,
			InsurancePrice,
		},
		data() {
			return {
				dicts: {
					schemeIdList: [],
					schemeIdListState: 'before',
				},
				config: {},
				deptList: {
					company: [], //公司
					department: [], // 组织
				},
				cityList: [],
				planDicts: {
					levelList: [],
					packagelList: [],
					supplierList: [],
				},
			};
		},
		props: {
			value: {
				required: true,
			},
			state: {
				required: false,
				default: 'write',
			},
			type: {
				required: false,
				type: String,
			},
			from: {
				required: false,
				type: String,
			},
		},
		computed: {
			infoData: {
				get() {
					// return this.value;
					return this.useVModel.call(this);
				},
				set(val) {
					this.$emit('input', val);
				},
			},
		},
		provide() {
			return {
				details_forecast: () => this.infoData,
				_dicts: () => this.dicts,
				details_config: () => this.config,
				_from: 'apply',
				deptList: this.deptList,
			};
		},
		created() {
			let unwatch = this.$watch(
				'infoData',
				val => {
					if (
						this.notEmpty(val) &&
						this.dicts.schemeIdListState == 'before'
					) {
						this.getAuthorizedProductSchemes();
					}
					if (unwatch) {
						unwatch?.();
					}
				},
				{
					immediate: true,
				},
			);
			this.init();
			this.getRegionList();
			this.getLevelList();
			this.getPackagelList();
			this.getSupplierList();
		},
		mounted() {},
		methods: {
			getSupplierList() {
				let params = {
					businessTypeCode: '6',
				};
				apis.SupplierlList(params).then(res => {
					if (res.code == 200) {
						this.planDicts.supplierList = res.data ?? [];
					}
				});
			},
			computeAll() {
				return this.$refs.CarInfo.computeAll();
			},
			getLevelList() {
				apis.LevelList({}).then(res => {
					if (res.code == 200) {
						this.planDicts.levelList = res.data;
					}
				});
			},
			getPackagelList() {
				apis.PackagelList({}).then(res => {
					if (res.code == 200) {
						this.planDicts.packagelList = res.data;
					}
				});
			},
			getRegionList() {
				regionList({
					regionLevel: 2,
					areaId: null,
				}).then(res => {
					if (res.code == 200) {
						this.cityList = res.data.filter(
							e => e.regionLevel === 3,
						);
					}
				});
			},
			init() {
				this.getDeptList(1);
				this.getDeptList(2);
			},
			getDeptList(deptType) {
				let params = {
					deptType,
				};
				app.DeptListNoPermission(params).then(res => {
					if (res.code == 200) {
						res?.data?.map(item => {
							item.deptId = item.deptId?.toString();
						});
						switch (deptType) {
							case 1:
								this.deptList.department = res?.data ?? [];
								break;
							case 2:
								this.deptList.company = res?.data ?? [];
								break;
						}
					}
				});
			},
			getFormData(type) {
				this.$refs.contract.getFormData(type);
			},
			getRentType(businessSource, leasingType) {
				let reny = '';
				if (businessSource == '1' && leasingType == '1') {
					reny = '3';
				}
				if (businessSource == '1' && leasingType == '2') {
					reny = '4';
				}
				if (businessSource == '2' && leasingType == '1') {
					reny = '1';
				}
				if (businessSource == '2' && leasingType == '2') {
					reny = '2';
				}
				return reny;
			},
			setConfig(type, config) {
				let item = {};
				if (config) {
					item = config;
				} else {
					item = this.dicts.schemeIdList.find(
						e =>
							e.id.toString() ==
							this.infoData.schemeId?.toString(),
					);
					item?.quotationCustomerTypeIrrList?.forEach(e => {
						e.quotationCustomerTypeId =
							e.quotationCustomerTypeId.toString();
					});
				}

				if (this.notEmpty(item)) {
					console.log(item);
					this.infoData.schemeSnapshootData = this.Base64.encode(
						JSON.stringify(item),
					);
					this.config = item;
					this.infoData.rentType_raw = item.leasingType;

					if (type !== 'init') {
						this.infoData.schemeName = item.schemeName;
						this.infoData.schemeCode = item.schemeNo;
						this.infoData.rentType = this.getRentType(
							item.businessSource,
							item.leasingType,
						);

						this.infoData.customerType = undefined;
						if (item.applicableType !== 0) {
							this.infoData.sourceBusinessType =
								item.applicableType.toString();
						} else {
							this.infoData.sourceBusinessType = undefined;
						}
						// if (
						// 	this.infoData.sourceBusinessType !==
						// 	item.businessSource.toString()
						// ) {
						// 	this.infoData?.productList?.map(item => {
						// 		item.maintenancePrice = undefined;
						// 	});
						// }

						// this.infoData.sourceBusinessType =
						// 	item.businessSource.toString();

						if (item.vehicleSource.toString() == '1') {
							this.infoData.carType = '1';
							this.infoData.carSourceType = '1';
						}
						if (item.vehicleSource.toString() == '2') {
							this.infoData.carType = '2';
							this.infoData.carSourceType = '2';
						}
						if (item.vehicleSource.toString() == '3') {
							this.infoData.carType = '2';
							this.infoData.carSourceType = '1';
						}
						this.infoData.guaranteeContract = undefined;
						this.infoData.leaseContract = undefined;
						this.infoData.salesContract = undefined;
						this.infoData.productList = [
							{
								plan: {
									planDriverType: '2',
									planFuelType: '2',
								},
								maintenanceMileageType: '1',
								insuranceList: [],
								maintenanceList: [],
								attachedDecorationList: [],
								feeList: [],
								planConf: {},
							},
						];
					}
					this.$refs.Plan?.setDisabled?.();
					this.$emitter.on('setDisabledOther');
					this.$emitter.on('setDisabledRefitted');
				} else {
					this.infoData.schemeSnapshootData = null;
					this.$message.error('未查找到预设产品方案！');
				}
				this.$forceUpdate();
			},

			getAuthorizedProductSchemes() {
				this.dicts.schemeIdListState = 'ing';

				let businessSource =
					this.$store.state.user?.userInfo?.businessType;
				apis.AuthorizedProductSchemes()
					.then(res => {
						if (res.code == 200) {
							this.dicts.schemeIdListState = 'end';
							this.dicts.schemeIdList = res.data?.filter(item => {
								if (businessSource == '3') {
									return true;
								}

								if (
									this.infoData.schemeId?.toString() ===
									item.id
								) {
									return true;
								}
								if (item.applicableType?.toString() == '0') {
									return true;
								}
								return item.applicableType == businessSource;
							});

							try {
								if (this.infoData?.schemeSnapshootData) {
									let config = JSON.parse(
										this.Base64.decode(
											this.infoData?.schemeSnapshootData,
										),
									);
									if (
										res.data.findIndex(
											e => e.id == config.id,
										) == -1
									) {
										console.log('有旧方案');
										console.log(this._.cloneDeep(config));
										this.dicts.schemeIdList.push(config);
									}
								}
							} catch (error) {
								console.log(error);
							}
							if (
								this.type == 'update' ||
								this.type == 'preview'
							) {
								this.setConfig('init');
							}
						}
					})
					.catch(() => {
						this.dicts.schemeIdListState = 'before';
					})
					.finally(() => {});
			},
			valid() {
				return new Promise(async resolve => {
					let result = true;
					let refs = Object.values(this.$refs);
					for (let index = 0; index < refs?.length; index++) {
						const ref = refs[index];
						if (
							Object.prototype.toString.call(ref) ==
							'[object Array]'
						) {
							for (let i = 0; i < ref.length; i++) {
								const element = ref[i];
								if (element?.valid) {
									let rc = await element?.valid?.();
									result = result && rc;
								}
								if (element?.validate) {
									let rf = await this._valid(ref);
									result = result && rf;
								}
								if (element?.form_validate) {
									let rf = await this._valid(
										ref,
										'form_validate',
									);
									result = result && rf;
								}
							}
						} else {
							if (ref?.valid) {
								let rc = await ref?.valid?.();
								result = result && rc;
							}
							if (ref?.validate) {
								let rf = await this._valid(ref);
								result = result && rf;
							}
							if (ref?.form_validate) {
								let rf = await this._valid(
									ref,
									'form_validate',
								);
								result = result && rf;
							}
						}
					}

					resolve(result);
				});
			},
		},
	};
</script>

<style lang="scss" scoped></style>
